package com.starlinkdt.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import com.starlinkdt.common.context.RequestIdContextHolder;
import com.starlinkdt.common.enums.BusinessStatus;
import com.starlinkdt.common.enums.HttpMethod;
import com.starlinkdt.common.utils.ServletUtils;
import com.starlinkdt.common.utils.StringUtils;
import com.starlinkdt.common.utils.ip.AddressUtils;
import com.starlinkdt.common.utils.ip.IpUtils;
import com.starlinkdt.common.utils.uuid.IdUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求日志记录处理
 *
 * @author system
 */
@Aspect
@Component
public class GlobalRequestLogAspect
{
    private static final Logger log = LoggerFactory.getLogger(GlobalRequestLogAspect.class);

    /** 计算操作消耗时间 */
    private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<Long>("Cost Time");

    @Pointcut("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
    public void globalRequestLogAspect() { }

    /**
     * 处理请求前执行
     */
    @Before(value = "globalRequestLogAspect()")
    public void boBefore(JoinPoint joinPoint) {
        // 设置Request-ID
        RequestIdContextHolder.setContext(IdUtils.simpleUUID());

        // 设置开始请求时间
        TIME_THREADLOCAL.set(System.currentTimeMillis());
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "globalRequestLogAspect()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "globalRequestLogAspect()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 设置日志记录格式
            String logFormat = "GlobalRequestLogAspect："
                    + "[REQUEST_ID : {}] [COST_TIME : {}ms] [STATUS : {}] [ERROR_MSG : {}] "
                    + "[IP : {}] [ADDRESS : {}] [URL : {}] [HTTP_METHOD : {}] [CLASS_METHOD : {}] "
                    + "[REQUEST : {}] [RESPONSE : {}] [HEADER : {}]";

            List<String> logArg = new ArrayList<>();

            // 请求ID
            logArg.add(RequestIdContextHolder.getContext());
            // 消耗时间
            logArg.add(String.valueOf(System.currentTimeMillis() - TIME_THREADLOCAL.get()));
            // 请求STATUS
            int status = BusinessStatus.SUCCESS.ordinal();
            String errorMsg = "";
            if (e != null) {
                status = BusinessStatus.FAIL.ordinal();
                errorMsg = e.getMessage();
            }
            logArg.add(String.valueOf(status));
            logArg.add(errorMsg);
            // 请求IP
            String requestIp = IpUtils.getIpAddr();
            logArg.add(requestIp);
            // 请求地址
            logArg.add(AddressUtils.getRealAddressByIP(requestIp));
            // 请求URL
            logArg.add(ServletUtils.getRequest().getRequestURL().toString());
            // 请求METHOD
            String requestMethod = ServletUtils.getRequest().getMethod();
            logArg.add(requestMethod);
            // CLASS_METHOD
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            logArg.add(className + "." + methodName);
            // 请求PARAMS
            logArg.add(getRequestValue(joinPoint, requestMethod));
            // 请求RESPONSE
            logArg.add(JSON.toJSONString(jsonResult));
            // 请求HEADER
            Map<String, String> requestHeaders = new HashMap<>();
            Enumeration<String> requestHeaderNames = ServletUtils.getRequest().getHeaderNames();
            while (requestHeaderNames.hasMoreElements()) {
                String requestHeaderName = requestHeaderNames.nextElement();
                String requestHeaderValue = ServletUtils.getRequest().getHeader(requestHeaderName);
                requestHeaders.put(requestHeaderName, requestHeaderValue);
            }
            logArg.add(JSON.toJSONString(requestHeaders));

            // 记录请求日志
            log.info(logFormat, logArg.toArray());
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
        } finally {
            // 清除开始请求时间
            TIME_THREADLOCAL.remove();
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param requestMethod 请求方式
     * @throws Exception 异常
     */
    private String getRequestValue(JoinPoint joinPoint, String requestMethod) throws Exception {
        Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
        if (StringUtils.isEmpty(paramsMap)
                && (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))) {
            return argsArrayToString(joinPoint.getArgs());
        } else {
            return JSON.toJSONString(paramsMap);
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        String jsonObj = JSON.toJSONString(o);
                        params.append(jsonObj).append(" ");
                    }
                    catch (Exception ignored) { }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    private boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

}
